#include "stdafx.h"

#include <MyFC/Button.h>

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

namespace My {

Button::Button()
{ 
	m_State = Neutral;
	m_Hover = false;
	m_Pressed = false;
}

void Button::UpdateState()
{
	if (!ControlEnabled(this)) 
	{
		SetState(Neutral);
		if (HasCapture())
			ReleaseMouse();
		return;
	}

	if (m_Hover)		
		SetState(m_Pressed ? Down : Hover);
	else
		SetState(Neutral);
}

void Button::SetState(State s)
{
	if (s != m_State) {
		m_State = s;
		Invalidate();
	}
}

void Button::HandleLeftDoubleClick(unsigned int flags, const CPoint & p)
{
	// Simulate a normal click...
	HandleLeftDown(flags, p);
	Update();
	Sleep(100);
	HandleLeftUp(flags, p);
}

void Button::HandleLeftDown(unsigned int flags, const CPoint & p)
{
	if (!ControlEnabled(this))
		return;
	m_Pressed = true;
	CaptureMouse();
	UpdateState();
	Control::HandleLeftDown(flags, p);
}

void Button::HandleLeftUp(unsigned int flags, const CPoint & p)
{
	if (!ControlEnabled(this))
		return;

	if (m_Pressed & m_Hover)
		HandleClick();
	m_Pressed = false;
	ReleaseMouse();
	UpdateState();
	Control::HandleLeftUp(flags, p);
}

void Button::HandleMouseMove(unsigned int flags, const CPoint & p)
{
	if (!ControlEnabled(this))
		return;

	bool in = ClientRect().PtInRect(p) != 0;
	if (in != m_Hover)
	{
		m_Hover = in;
		UpdateState();
	}
	Control::HandleMouseMove(flags, p);
}



} // My
